//
//  ViewController.swift
//  二维码扫描
//
//  Created by Nick xu on 16/8/3.
//  Copyright © 2016年 hddden. All rights reserved.
//
    

import UIKit
import Foundation
import AVFoundation
let comeraWidth:CGFloat = 250
let minHeight:CGFloat = 100

protocol AVQRCodeViewManagerInputDelegate : NSObjectProtocol {
    func finishScan(_ msg: String?)
}

class AVQRCodeViewManager: UIView, AVCaptureMetadataOutputObjectsDelegate {
    //MARK: - property
    weak var delegate:inputViewProtocol?
    weak var InputDelegate: AVQRCodeViewManagerInputDelegate?
    weak var activeTextfield:UITextField?
    weak var comeraView: UIView?
    weak var contraintHeight: NSLayoutConstraint?
    static let shareAVQRCodeViewManager:AVQRCodeViewManager = {
        let view = AVQRCodeViewManager(frame: UIScreen.main.bounds)
        view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
        return view
    }()
    
    let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
    let session = AVCaptureSession()
    var codeLayer : AVCaptureVideoPreviewLayer?
    //MARK: - life cycle
    fileprivate override init(frame: CGRect) {
        super.init(frame: frame)
        //添加边框
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: comeraWidth, height: comeraWidth))
        imageView.image = UIImage(named: "pick_bg")
        self.setUPConfig()
        self.setupCamera()
        self.addSubview(imageView)
        self.addSubview(cancelButton)//添加取消按钮
        self.addSubview(cutCodeStyleButton)
        self.addSubview(backImageView)
        self.addSubview(lightButton)
        self.backImageView.addSubview(indectorView)
        indectorView.frame = CGRect(x: 2, y: -19, width: 0, height: 0)
        indectorView.sizeToFit()
//        self.cancelButton.snp.makeConstraints { (make) in
////            make.trailing.equalTo(self).offset(5)
////            make.top.equalTo(self).offset(-5)
////            make.width.equalTo(44)
////            make.height.equalTo(44)
//            make.center.equalTo(self)
//        }
//        let width:CGFloat = 100
//        let height:CGFloat = 35
//        let x = CGRectGetMaxX(backImageView.frame) - width
//        let y = CGRectGetMaxY(backImageView.frame) + 50
//        let x2 = codeLayer?.frame.origin.x
//        cancelButton.frame = CGRectMake(x, y, width, height)
//        cutCodeStyleButton.frame = CGRectMake(x2!, y, width, height)
//        backImageView.frame = CGRectMake((codeLayer?.frame.origin.x)! - 2 , (codeLayer?.frame.origin.y)! - 2, comeraWidth + 4, comeraWidth + 4)
        backImageView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.centerY.equalTo(self)
            make.width.equalTo(comeraWidth)
            make.height.equalTo(comeraWidth)
        }
        cutCodeStyleButton.snp.makeConstraints { (make) in
            make.leading.equalTo(backImageView)
            make.top.equalTo(backImageView.snp.bottom).offset(50)
            make.width.equalTo(115)
            make.height.equalTo(30)
        }
        cancelButton.snp.makeConstraints { (make) in
            make.trailing.equalTo(self.backImageView)
            make.top.equalTo(backImageView.snp.bottom).offset(50)
            make.height.equalTo(30)
            make.width.equalTo(115)
        }
        lightButton.snp.makeConstraints { (make) in
            make.top.equalTo(backImageView.snp.bottom).offset(10)
            make.centerX.equalTo(self)
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func willMove(toSuperview newSuperview: UIView?) {
        self.session.startRunning()
    }
    override func didMoveToSuperview() {
//        self.indectorView.snp.updateConstraints { (make) in
//            make.topMargin.equalTo(240)
//        }
        
        UIView.animate(withDuration: self.cutCodeStyleButton.isSelected ? 1.5 : 2, delay: 0, options: UIViewAnimationOptions.repeat, animations: {
            self.indectorView.y = self.cutCodeStyleButton.isSelected ? minHeight - 4 : comeraWidth - 4
//            self.layoutIfNeeded()
            }) { (true) in
                self.indectorView.y = -19
//                self.indectorView.snp.updateConstraints { (make) in
//                    make.topMargin.equalTo(2)
//                }
        }
    }
    //MARK: - public
    class func showComera(){
        let window = UIApplication.shared.delegate?.window
        window!!.addSubview(AVQRCodeViewManager.shareAVQRCodeViewManager)
    }
    //MARK: - private
    func setUPConfig() {
        NotificationCenter.default.addObserver(self, selector: #selector(CaptuvoDecoderManager.newEnditingBegin(_:)), name: NSNotification.Name.UITextFieldTextDidBeginEditing, object: nil)
        
    }
    
    func newEnditingBegin(_ notification: Notification){
        let object:UITextField = (notification.object as? UITextField)!
        self.activeTextfield = object
    }

    func setupCamera(){
        //TODO: 高质量采集率
        self.session.sessionPreset = AVCaptureSessionPresetHigh
        var error : NSError?
         //TODO: 输入流
        let input: AVCaptureDeviceInput!
        do{
            input = try AVCaptureDeviceInput(device: device)
        }
        catch let error1 as NSError{
            error = error1
            input = nil
        }
        if error != nil {
            return
        }
        if session.canAddInput(input) {
            session.addInput(input)
        }
         //TODO: 显示图像
        codeLayer = AVCaptureVideoPreviewLayer(session: session)
        codeLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill
//        self.backImageView.frame = CGRectMake(KscreenWidth / 2 - comeraWidth / 2, KscreenHeight / 3 - comeraWidth / 2 , comeraWidth, comeraWidth)
//        backImageView.layer.addSublayer(codeLayer!)
        codeLayer?.frame = CGRect(x: 0, y: 0, width: KscreenWidth, height: KscreenHeight)
        self.layer.addSublayer(codeLayer!)
        backImageView.clipsToBounds = true
//        codeLayer?.frame = CGRectMake(2, 2, comeraWidth - 4, comeraWidth - 4)
//        codeLayer.centerX = KscreenWidth / 2
//        codeLayer.centerY = KscreenHeight / 2.5
//        codeLayer.bounds = CGRectMake(0, 0, comeraWidth, comeraWidth)
//        self.layer.insertSublayer(self.codeLayer!, atIndex: 0)
        let output = AVCaptureMetadataOutput()
        output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        if session.canAddOutput(output) {
            session.addOutput(output)
            //设置扫码支持的编码格式（如下设置各种条形码和二维码兼容）
            output.metadataObjectTypes = [ AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeCode39Code,AVMetadataObjectTypeUPCECode,AVMetadataObjectTypePDF417Code,
                                           AVMetadataObjectTypeAztecCode,
                                           AVMetadataObjectTypeCode93Code,
                                           AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeCode39Mod43Code];
            //            output.rectOfInterest = CGRectMake(0, 0, 1, 0)
        }
    }
    
    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
        
        var stringValue:String?
        if metadataObjects.count > 0 {
            let metadataObject = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
            
            stringValue = metadataObject.stringValue
        }
        NotificationCenter.default.post(name: Notification.Name(rawValue: "finishScanCode"), object: nil)//发送消息完成的通知
        self.removeFromSuperview()
        self.session.stopRunning()
        self.activeTextfield?.text = stringValue
        if let delegate = self.delegate {
            delegate.finishInput(stringValue)
        }
        if let delegate = self.InputDelegate {
            delegate.finishScan(stringValue)
        }
    }
    //MARK: - UIResponse
    func clickLightButton(_ button : UIButton){
        
        do{
            try device?.lockForConfiguration()
        }catch{
           
        }
        if device?.torchMode == AVCaptureTorchMode.off {
            device?.torchMode = AVCaptureTorchMode.on
        }else{
             device?.torchMode = AVCaptureTorchMode.off
        }
        device?.unlockForConfiguration()
    }
    func clickCancelButton(_ button: UIButton){
        self.removeFromSuperview()
        do{
            try device?.lockForConfiguration()
        }catch{
            
        }
        if device?.torchMode == AVCaptureTorchMode.on {
            device?.torchMode = AVCaptureTorchMode.off
        }
        device?.unlockForConfiguration()
    }
    func clickcutCodeStyleButton(_ button: UIButton){
        self.indectorView.layer.removeAllAnimations()
        self.indectorView.isHidden = true
        button.isSelected = !button.isSelected
        if button.isSelected {
            backImageView.snp.remakeConstraints { (make) in
                make.centerX.equalTo(self)
                make.centerY.equalTo(self)
                make.width.equalTo(comeraWidth)
                make.height.equalTo(minHeight)
            }
            UIView.animate(withDuration: 0.5, animations: {
//                self.cancelButton.y -= comeraWidth - minHeight
//                self.cutCodeStyleButton.y -= comeraWidth - minHeight
//                self.backImageView.height -= comeraWidth - minHeight
                self.layoutIfNeeded()
                }, completion: { (true) in
//                    self.codeLayer?.frame = CGRectMake(2, 2, comeraWidth - 4, minHeight - 4)
                    self.indectorView.y = -19
                    self.indectorView.isHidden = false
                    UIView.animate(withDuration: 1.5, delay: 0, options: UIViewAnimationOptions.repeat, animations: {
                        self.indectorView.y = minHeight - 2 - self.indectorView.height
                        //            self.layoutIfNeeded()
                    }) { (true) in
                        self.indectorView.y = -19
                        //                self.indectorView.snp.updateConstraints { (make) in
                        //                    make.topMargin.equalTo(2)
                        //                }
                    }
            })
        }else{
//            codeLayer?.frame = CGRectMake(2, 2, comeraWidth - 4, comeraWidth - 4)
          
            backImageView.snp.remakeConstraints { (make) in
                make.centerX.equalTo(self)
                make.centerY.equalTo(self)
                make.width.equalTo(comeraWidth)
                make.height.equalTo(comeraWidth)
            }
//            UIView.animateWithDuration(0.5, animations: {
////                self.codeLayer?.frame = CGRectMake(KscreenWidth / 2 - comeraWidth / 2, KscreenHeight / 2.5 - comeraWidth / 2, comeraWidth, comeraWidth)
////                self.cancelButton.y += comeraWidth - minHeight
////                self.cutCodeStyleButton.y += comeraWidth - minHeight
////                self.backImageView.height += comeraWidth - minHeight
//                self.layoutIfNeeded()
//            })
            
            UIView.animate(withDuration: 0.5, animations: { 
                  self.layoutIfNeeded()
                }, completion: { (true) in
                     self.indectorView.y = -19
                    self.indectorView.isHidden = false
                    UIView.animate(withDuration: 2, delay: 0, options: UIViewAnimationOptions.repeat, animations: {
                        self.indectorView.y = comeraWidth - 2 - self.indectorView.height
                        //            self.layoutIfNeeded()
                    }) { (true) in
                        self.indectorView.y = 2
                        //                self.indectorView.snp.updateConstraints { (make) in
                        //                    make.topMargin.equalTo(2)
                        //                }
                    }
            })
        }
    }
    //MARK: - lazyloading
    lazy fileprivate var cancelButton:UIButton = {
        let button = UIButton()
        button.setTitle("取消", for: UIControlState())
        button.layer.cornerRadius = 5
        button.setTitleColor(UIColor.white, for: UIControlState())
        button.backgroundColor = UIColor.darkGray
//        button.setImage(UIImage(named: "closed"), forState: UIControlState.Normal)
        button.addTarget(self, action: #selector(AVQRCodeViewManager.clickCancelButton(_:)), for: UIControlEvents.touchUpInside)
        return button
    }()
    lazy fileprivate var cutCodeStyleButton:UIButton = {
        let button = UIButton()
//        button.setTitle("取消", forState: UIControlState.Normal)
        button.setTitle("一维码", for: UIControlState())
        button.setImage(UIImage(named: "barcode"), for: UIControlState())
        button.setTitle("二维码", for: UIControlState.selected)
        button.setImage(UIImage(named: "qrCode"), for: UIControlState.selected)
        button.layer.cornerRadius = 5
        button.setTitleColor(UIColor.white, for: UIControlState())
        button.backgroundColor = UIColor.darkGray
        //        button.setImage(UIImage(named: "closed"), forState: UIControlState.Normal)
        button.addTarget(self, action: #selector(AVQRCodeViewManager.clickcutCodeStyleButton(_:)), for: UIControlEvents.touchUpInside)
        return button
    }()
    lazy fileprivate var backImageView:UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "comeraBorder")
        return imageView
    }()
    lazy fileprivate var lightButton:UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "夜灯"), for: UIControlState())
        button.addTarget(self, action: #selector(AVQRCodeViewManager.clickLightButton(_:)), for: UIControlEvents.touchUpInside)
        return button
    }()
    lazy fileprivate var indectorView:UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "scanIndector"))
        return imageView
    }()

}

